package vip.george.security.autoconfig;


import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;


@ConfigurationProperties(prefix = "interface.encrypt")
public class EncryptProperties {

    /**
     * AES密钥
     */
    private String aesKey;

    /**
     * RSA私钥
     */
    private String rsaPrivateKey;

    /**
     * 不需要加密的url
     */
    private Set<String> excludeUrls = new HashSet<>();

    /**
     * 加解密的方式
     */
    private String securityMode = "RSA_AND_AES_MIX";


    /**
     * 加解密方式
     */
    public enum SecurityMode {

        AES("AES"),

        RSA_AND_AES_MIX("RSA_AND_AES_MIX"),
        ;

        /**
         * 值
         */
        private String value;

        SecurityMode(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        /**
         * 根据valuse获取对应的枚举
         */
        public static SecurityMode getByValue(String value) {
            for (SecurityMode securityMode : SecurityMode.values()) {
                if (securityMode.getValue().equals(value)) {
                    return securityMode;
                }
            }
            return null;
        }
    }


    @PostConstruct
    public void init() {
        SecurityMode model = SecurityMode.getByValue(securityMode);
        if (Objects.isNull(model)) {
            throw new IllegalStateException("param [interface.encrypt.securityMode] model not support");
        }

        if (SecurityMode.AES.equals(model)) {
            if (StringUtils.isBlank(aesKey)) {
                throw new IllegalStateException(SecurityMode.AES + "model, param [interface.encrypt.aesKey] must be configured");
            }
        } else if (SecurityMode.RSA_AND_AES_MIX.equals(model) ) {
            if (StringUtils.isBlank(rsaPrivateKey)) {
                throw new IllegalStateException(SecurityMode.RSA_AND_AES_MIX + "model, param [interface.encrypt.rsaPrivateKey] must be configured");
            }
        }
    }


    public String getAesKey() {
        return aesKey;
    }

    public void setAesKey(String aesKey) {
        this.aesKey = aesKey;
    }

    public String getRsaPrivateKey() {
        return rsaPrivateKey;
    }

    public void setRsaPrivateKey(String rsaPrivateKey) {
        this.rsaPrivateKey = rsaPrivateKey;
    }

    public Set<String> getExcludeUrls() {
        return excludeUrls;
    }

    public void setExcludeUrls(Set<String> excludeUrls) {
        this.excludeUrls = excludeUrls;
    }

    public String getSecurityMode() {
        return securityMode;
    }

    public void setSecurityMode(String securityMode) {
        this.securityMode = securityMode;
    }
}
